/** --main js--* */

$(function () {

    $("#logout").click(function () {
        logout();
    });
    var logout = function () {
        if (confirm("是否注销当前登录？")) {
            deleteCookie('___USER_TOKEN');
            deleteCookie("CTRL_DEVICE_ID");
            deleteCookie("deviceId");
            window.top.location.href = './login.html';
        }
    };
    getUserInfo();
});


function jugeDeviceOnline() {
    $.ajax({
        url: window.queryDyncUrl,
        type: "GET",
        dataType: "json",
        success: function (reData) {
            if (reData.online) {
                getFlowAfterOnline();
            }
        }
    });
}

// 获取登录用户信息
function getUserInfo() {
    $.ajax({
        url: '/services/api/account/user/userinfo',
        type: "GET",
        dataType: "json",
        success: function (data) {
            $("#userinfo").html(data.nickName + ",你好！");
//            if (data && data.name && data.name.toLowerCase().startsWith("kf") && !$("#IS_KF_PAGE").html()) {
//                window.top.location.href = './service.html';
//            }

//            var show_icon = data.icon && data.icon != '' ? (_config.url_file + '/show/' + data.icon) : './res/images/user.png';
//            $("#userimg").attr("src", show_icon);
        }
    });
}

function getDeviceDyncInfo() {
    // alert('getDeviceInfo')
    var data = {
        id: genUUID(),
        type: "post",
        status: 0,
        path: "/systemCommTo",
        header: {
            to: window.CTRL_DEVICE_ID
        },
        body: {
            path: '/common/device/putInfo',
            type: 'put',
            body: {
                type: 'power,netType'
            }
        }
    };
    webSocket_send(data);
}

function getFlowAfterOnline() {
    var data = {
        id: genUUID(),
        type: "post",
        status: 0,
        path: "/systemCommTo",
        header: {
            to: window.CTRL_DEVICE_ID
        },
        body: {
            path: '/common/device/putInfo',
            type: 'put',
            body: {
                type: 'flow'
            }
        }
    };
    webSocket_send(data);
}

(function () {

    var _ctrl_device_id = getCookie("CTRL_DEVICE_ID");
    window.CTRL_DEVICE_ID = _ctrl_device_id;
    initWebsocket();
    // 对于所有命令的回调
    var _systemCommTo = function (respData, reqData) {
        if (reqData == null) {
            if (respData.body != null) {
                if (respData.body.path == '/sync/notifi') {
                    $.ajax({url: _config.base_url + '/sync/get', beforeSend: function (xhr) {
                        xhr.setRequestHeader('If-None-Match', window.PushedETag);
                        console.log("--------------------------");
                    }, success: function (responseData) {

                    }});
                }
            }

        } else {
            // alert(JSON.stringify(reqData));
            if (reqData.body.path == '/common/device/putInfo') {
                console.log(reqData);
            }
            $("iframe").each(function (i, iframe) {
               // console.log(iframe);
                if (iframe.contentWindow.msgCallBack) {
                    iframe.contentWindow.msgCallBack(respData);
                }
            });
            if ($('#iframePage')[0].contentWindow.msgCallBack) {
                $('#iframePage')[0].contentWindow.msgCallBack(respData);
            }
        }
    }

// angular js
    angular.module("main", []);

    var _AllDocCtrl = function ($rootScope, $scope, $location) {

        // getDeviceDyncInfo();
        // setInterval(getDeviceDyncInfo, 1000 * 60 * 1);
        //setInterval(getFlowAfterOnline, 1000 * 60);
        $.ajax({
            url: window.queryDeviceUrl,
            type: "GET",
            dataType: "json",
            success: function (data) {
                $rootScope.device = data;
                window.applyAngularScope($rootScope, $scope);
            }
        });

        $scope.getPowerStatus = function () {
            //getDeviceDyncInfo();
        }

        $scope.checkStatus = function () {
            $.ajax({
                url: window.queryDyncUrl,
                type: "GET",
                dataType: "json",
                success: function (reData) {
                    var data = reData.device;
                    if (reData.online) {
                        window.connStatus = true;
                        // 设置电量显示图标上的电量
                        data.power = data.power > 100 ? 100 : data.power; // 电量不能太大了
                        if (data.power <= 20) {
                            var p = 18 * (data.power / 100);
                            data.power = "剩余" + data.power + "%";
                            $(".u-battery-power").css("background-color", "red");
                            $(".u-battery-power").css("width", p + "px");
                        } else if (data.power >= 50) {
                            var p = 18 * (data.power / 100);
                            data.power = "剩余" + data.power + "%";
                            $(".u-battery-power").css("background-color", "#71FD13");
                            $(".u-battery-power").css("width", p + "px");
                        } else {
                            var p = 18 * (data.power / 100);
                            data.power = "剩余" + data.power + "%";
                            $(".u-battery-power").css("background-color", "yellow");
                            $(".u-battery-power").css("width", p + "px");
                        }
                        if (data.netType) {
                            data.netTypeClass = "u_icon-" + data.netType;
                        } else {
                            data.netTypeClass = "u_icon-wifi";
                        }
                        data.wifiStatus = "设备在线";
                    } else {
                        window.connStatus = false;
                        $(".u-battery-power").css({
                            "width": "18px",
                            "background": "#849cb0",
                            "border-top": "1px solid #849cb0"
                        });
                        if (data) {
                            data.power = "未知";
                            data.netTypeClass = "u_icon-nowifi";
                            data.wifiStatus = "设备离线";
                        } else {
                            data = {
                                "power": "未知",
                                "netTypeClass": "u_icon-nowifi",
                                "wifiStatus": "设备离线"
                            };
                        }
                    }
                    $rootScope.deviceDync = data;
                    // alert(window.iframe.window.statusChange);
                    if ($('#iframePage')[0].contentWindow.statusChange) {
                        $('#iframePage')[0].contentWindow.statusChange(reData.online);
                    }
                    window.applyAngularScope($rootScope, $scope);
                }
            });
        }
        $scope.checkStatus();
    }

    window.queryDyncUrl = window._config.base_url + "/common/device/dync/" + window.CTRL_DEVICE_ID;
    window.queryDeviceUrl = window._config.base_url + "/common/device/queryDeviceById" + "?deviceId=" + window.CTRL_DEVICE_ID;

    window.systemCommTo = _systemCommTo;
    window.AllDocCtrl = _AllDocCtrl;

})();


window.commonModal = {
    modal: $("#commonModal"),
    /**
     *
     * @param url
     * @param title
     * @param callback
     */
    show: function (url, title, callback) {
        var _self = this;
        if (_self.modal && url && title) {
            _self.iframeSrc = url;
            $("[title]", _self.modal).html(title);
            $("iframe", _self.modal).attr("src", url + "?t=" + new Date().getTime());
            setTimeout(function () {
                _self.modal.modal("show").unbind("hidden").on("hidden",function () {
                    if (callback && _self.needreload) {
                        callback();
                    }
                }).unbind("shown").on("shown", function () {
                        $(this).css("z-index", 2000);
                    });
            }, 200);
        }
    },
    show2: function (url, title, callback) {
        var _self = this;
        if (_self.modal && url && title) {
            _self.iframeSrc = url;
            $("[title]", _self.modal).html(title);
            $("iframe", _self.modal).attr("src", url);
            setTimeout(function () {
                _self.modal.modal("show").unbind("hidden").on("hidden",function () {
                    if (callback && _self.needreload) {
                        callback();
                    }
                }).unbind("shown").on("shown", function () {
                        $(this).css("z-index", 2000);
                    });
            }, 200);
        }
    },
    needreload: false,
    hide: function () {
        var _self = this;
        if (_self.modal) {
            _self.modal.modal("hide");
        }
    }
}

window.progressModal = {
    modal: $("#progressModal"),
    bar: $("#progressModal .bar"),
    txt: $("#progressModal #percent"),
    clearTime: 0,
    reset: function (percentName) {
        var _self = this;
        _self.txt.html("0%");
        _self.bar.css("width", "1%");
        $.get("/progress?percentName=" + percentName + "&reset=true&t=" + new Date().getTime(), function (data) {
        });
    },
    /**
     *
     * @param percentName
     * @param time
     * @param callback
     */
    show: function (percentName, time, callback) {
        var _self = this;
        _self.reset(percentName);
        if (_self.modal && percentName && time) {
            _self.clearTime = setInterval(function () {
                $.post("/progress?percentName=" + percentName + "&t=" + new Date().getTime(), function (data) {
                    if (data) {
                        _self.txt.html(data + "%");
                        _self.bar.css("width", data + "%");
                        console.log(data);
                        if (data >= 100 || data < 0) {
                            setTimeout(function () {
                                _self.hide();
                            }, 200);
                            clearInterval(_self.clearTime);
                        }
                    }
                });
            }, time);
            commonModal.modal.css("z-index", 1040);
            _self.modal.modal("show").unbind("hidden").on("hidden", function () {
                clearInterval(_self.clearTime);
                _self.bar.css("width", "0%");
                if (callback) {
                    callback();
                }
                commonModal.modal.css("z-index", 2000);
            });
        }
    },
    hide: function () {
        var _self = this;
        if (_self.modal) {
            _self.modal.modal("hide");
        }
    }
}


//系统时间显示设置
Date.prototype.Format = function (formatStr) {
    var str = formatStr;
    var Week = [ '日', '一', '二', '三', '四', '五', '六' ];
    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
    str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
    str = str.replace(/M/g, this.getMonth() + 1);
    str = str.replace(/w|W/g, Week[this.getDay()]);
    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());
    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());
    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());
    return str;
}
var timeInterval = setInterval("clock()", 1000)
function clock() {
    $("#nowTime").text(new Date().Format("yyyy-MM-DD hh:mm 星期w"));
}

$(function () {
    setTimeout(function () {
        if ($(".modal-backdrop").length > 0) {
            $(".modal-backdrop").remove();
        }
    }, 5000);
});